package com.app.utils.spring.properties;

import com.app.utils.base.j2se.Logger;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Description
 * Created by 王伟
 * Date create on 15:37 2019/11/13.
 */
public class Config{
    private static String[] propertyFileName = new String[]{"application.properties","config.properties","configUrls.properties"};

    public static Map<String, String> pp = new HashMap<>();

    public static void init(){
        for (String file : propertyFileName) {
            pp.putAll(getProperty(file));
        }
    }

    private static Map<String, String> getProperty(String file) {
        try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties(file);
            return processProperties(properties);
        } catch (IOException e) {
            Logger.error("读取配置异常:",e);
        }
        return new HashMap<>();
    }

    private static Map<String, String> processProperties(Properties props){
        Map<String, String> map = new HashMap<>();
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            try {
                // PropertiesLoaderUtils的默认编码是ISO-8859-1,在这里转码一下
                map.put(keyStr, new String(props.getProperty(keyStr).getBytes("ISO-8859-1"), "utf-8"));
            } catch (Exception e) {
                Logger.error("读取配置异常(字符转换):",e);
            }
        }
        return map;
    }
}
